package rwt.server.handlers;

import org.slf4j.*;

import rwt.server.*;
import rwt.server.RailroadMessages.MoveSlotsMsg;
import rwt.server.RailroadMessages.SlRdDataMsg;
import rwt.server.WebMessages.*;
import rwt.server.core.*;
import rwt.server.railroad.Train;

public class SlRdDataHandler extends MessageHandler<SlRdDataMsg>
{
	private static final Logger logger = LoggerFactory.getLogger(SlRdDataHandler.class);
	
	@Override
	public void handle(SlRdDataMsg message, IConnection source) throws Exception
	{
		logger.debug("OPC_SL_RD_DATA received! " + message.locoAddress + ", " + 
				message.isAddressAlreadyInUse + ", " + message.slot);
		
		if (message.isAddressAlreadyInUse)
		{
			logger.info("Railroad reports that train " + message.locoAddress + " is already in use!");
		}
		
		Train t = RailServer.getTrainManager().getTrainById(message.locoAddress);
		IClient client = RailServer.getClientManager().getClientById(t.getThrottleClientId());
		int slot = message.slot;
		
		t.setInitialized(slot, message.locoAddress, slot);
		
		// Grant throttle to client (opens Emergency Throttle window in client's browser)
		OpenThrottleResponse response = new OpenThrottleResponse(message.locoAddress, t.getPhysicalSlotNum(), true, true);
		client.write(response);
		
		// Inform all connected clients that this throttle has been opened 
		PutAvailableTrains availableTrainsMsg = RailServer.getTrainManager().getPutAvailableTrains();
		RailServer.getClientManager().sendToAll(availableTrainsMsg);
		
		// Referred to as a "null move" in the Lab Manual
		MoveSlotsMsg msg = new MoveSlotsMsg(slot, slot);
		RailServer.getRailroadServer().write(msg);
	}
}
